package com.taskmanagement.service;

import com.taskmanagement.mapper.StepMapper;
import com.taskmanagement.entity.Step;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

@Service
public class StepService {

    @Autowired
    private StepMapper stepMapper;
    
    @Autowired
    private TaskService taskService;

    public List<Step> findByTaskId(BigInteger taskId) {
        return stepMapper.findByTaskId(taskId);
    }

    public Step findById(BigInteger id) {
        return stepMapper.findById(id);
    }

    public Step createStep(Step step) {
        step.setIsCompleted(false);
        stepMapper.insert(step);
        return step;
    }

    public Step updateStep(Step step) {
        stepMapper.update(step);
        return step;
    }

    public boolean deleteStep(BigInteger id) {
        return stepMapper.delete(id) > 0;
    }

    public boolean updateStepStatus(BigInteger id, Boolean isCompleted) {
        Step step = stepMapper.findById(id);
        if (step == null) {
            return false;
        }
        
        Date actualEndDate = null;
        if (isCompleted && !step.getIsCompleted()) {
            actualEndDate = new Date();
        }
        
        return stepMapper.updateStatus(id, isCompleted, actualEndDate) > 0;
    }
    
    public int countByTaskId(BigInteger taskId) {
        return stepMapper.countByTaskId(taskId);
    }
    
    public int countCompletedByTaskId(BigInteger taskId) {
        return stepMapper.countCompletedByTaskId(taskId);
    }
    
    public double getTaskProgress(BigInteger taskId) {
        int total = countByTaskId(taskId);
        if (total == 0) {
            return 0.0;
        }
        int completed = countCompletedByTaskId(taskId);
        return (double) completed / total * 100;
    }
}
